    // function to round to two digits, if necessary
    function roundToTwo(num)
    {    
      return +(Math.round(num + "e+2")  + "e-2");
    }
    
    // Start a timer for the user and keeps track of powerup timers
    var interval; //used to track the interval and call function
    interval = setInterval(function()
      {
      time=time-1;
      elapsedTime=elapsedTime+1;
      
      document.getElementById("time").innerHTML="Time: "+time;
      //if the time hits 0 the user has run out of time. end the game
      if (time==0)
      {
        Crafty.scene('Victory');
        clearInterval(interval);
      };
      },1000);
    
    //how much to add when the timer is picked up and completing stages
      var timeAdd=3;
      var stageTimeAdd=4;
    
    //initalize the max number of coins as ints
      var max_yellow_coins = 5;
      var max_red_coins = 3;
      var max_green_coins = 0;
      var max_blue_coins = 0;
      
      var max_boots = 1;
      var max_clocks = 1;
      
      var max_multipliers = 1;
      
      var max_flames = 1;
      
      function updateCoinCounts()
      {
        if (stage < 5)
	{
	  max_yellow_coins = max_yellow_coins+2;
	  max_red_coins = max_red_coins+1;
	}
	else if (stage < 10)
	{
	  max_yellow_coins = max_yellow_coins+1;
	  max_red_coins = max_red_coins+2;
	}
	else if (stage==10)
	{
	  max_yellow_coins = 0;
	  max_red_coins = 5;
	  max_green_coins = 3;
	}
	else if (stage < 15)
	{
	  max_red_coins = max_red_coins+2;
	  max_green_coins = max_green_coins+1;
	}
	else if (stage < 20)
	{
	  max_red_coins = max_red_coins+1;
	  max_green_coins = max_green_coins+2;
	}
	else if (stage ==20)
	{
	  max_red_coins = 0;
	  max_green_coins = 5;
	  max_blue_coins = 3;
	}
	else if (stage < 25)
	{
	  max_green_coins = max_green_coins+2;
	  max_blue_coins = max_blue_coins + 1;
	}
	else
	{
	  max_green_coins = max_green_coins+1;
	  max_blue_coins = max_blue_coins + 2;
	}

      };
      
      function updateCounter()
      {
        time=time+stageTimeAdd;
        document.getElementById("time").innerHTML="Time: "+time;
      }
      
      function updateStage()
      {
        stage=stage+1;
        document.getElementById("stage").innerHTML="Stage: "+stage;
      }
      
      function updateClocksCount()
      {
	if (stage == 10)
	  max_clocks = max_clocks+1;
	else if (stage == 20)
	{ 
	  max_clocks = max_clocks+1;
	  timeAdd = 3;
	  stageTimeAdd = 3;
	}
	else if (stage == 30)
	{
	  max_clocks = max_clocks+1;
	  timeAdd=2;
	  stageTimeAdd = 2;
	}
	else if (stage == 40)
	{
	  stageTimeAdd = 1;
	}
      }
      
      function startBoost() {
	  
	//updates the boots HTML div
	
        document.getElementById("bootsHolding").className="visible"
	
      }
      
      function clockPickup() {
	time = time + timeAdd;
      }
      
      function multiplierPickup(multiplierDuration,multiplierOn) {
	var multiplierTime = multiplierDuration;
	multiplierOn = true;
	
	//checks if the multiTimer is defined already and if so, clears it
	if (typeof multiTimer != 'undefined') {
	clearInterval(multiTimer);
	  }
	  
	//starts the bonus timer, counting down to 0
	var multiTimer = setInterval(function(){
	  yellowCoin = 200;
	  redCoin = 400;
	  greenCoin = 800;
	  blueCoin = 2000;
	  document.getElementById("multiplierTime").className="visible"
	  document.getElementById("multiplierTime").innerHTML="2x Coins: "+ multiplierTime;
	  multiplierTime = multiplierTime - 1;
	  
	  if (multiplierTime == -1) {
	  multiplierOn = false;
	    yellowCoin = 100;
	    redCoin = 200;
	    greenCoin = 400;
	    blueCoin = 1000;
	    document.getElementById("multiplierTime").innerHTML="2x Coins: ";
	    document.getElementById("multiplierTime").className="hidden";
	    clearInterval(multiTimer);
	  };
	}, 1000);
      }

      function bootsTester() {
	if (speedBoost == true) {
	  playerSpeed = 4;
	  speedBoost = false;
	  document.getElementById("bootsHolding").className="hidden"
	  document.getElementById("bootsOn").className="visible"
	}
	else
	{
	  document.getElementById("bootsOn").className="hidden"
	  playerSpeed = 2;
	}
      }
      
      function stageDecider() {
	if (stage < 5) {
	  treeSprite = 'spr_tree3';
	  bushSprite = 'spr_bush2';
	  rockSprite = 'spr_rock8';
	  backgroundColor = 'rgb(68,132,14)';
	  stageName = "Field";
	  document.getElementById("stageName").innerHTML = "Stage Name: " + stageName;
	}
	else if (stage < 10) {
	  treeSprite = 'spr_tree4';
	  bushSprite = 'spr_bush';
	  rockSprite = 'spr_rock5';
	  backgroundColor = 'rgb(64,94,56)';
	  stageName = "Forest";
	  document.getElementById("stageName").innerHTML = "Stage Name: " + stageName;
	}
	else if (stage < 15) {
	  treeSprite = 'spr_tree6';
	  bushSprite = 'spr_tree2';
	  rockSprite = 'spr_rock9';
	  backgroundColor = 'rgb(41,62,34)';
	  stageName = "Deep Forest";
	  document.getElementById("stageName").innerHTML = "Stage Name: " + stageName;
	}
	else if (stage < 20) {
	  treeSprite = 'spr_rock7';
	  bushSprite = 'spr_bush3';
	  rockSprite = 'spr_rock4';
	  backgroundColor = 'rgb(65,67,64)';
	  stageName = "Cave";
	  document.getElementById("stageName").innerHTML = "Stage Name: " + stageName;
	}
	else if (stage < 25) {
	  treeSprite = 'spr_cactus2';
	  bushSprite = 'spr_bush4';
	  rockSprite = 'spr_rock5';
	  backgroundColor = 'rgb(165,170,79)';
	  stageName = "Desert";
	  document.getElementById("stageName").innerHTML = "Stage Name: " + stageName;
	  }
	else if (stage < 30) {
	  treeSprite = 'spr_tree7';
	  bushSprite = 'spr_stump';
	  rockSprite = 'spr_rock6';
	  backgroundColor = 'rgb(57,22,11)';
	  stageName = "Hell";
	  document.getElementById("stageName").innerHTML = "Stage Name: " + stageName;
	}
	else if (stage < 35)
	{
	  treeSprite = 'spr_rock9';
	  bushSprite = 'spr_cactus';
	  rockSprite = 'spr_cactus';
	  backgroundColor = 'rgb(8,146,238)';
	  stageName = "Bonus Stage: Fuchsia Gym (Invisible Obstacles)";
	  document.getElementById("stageName").innerHTML = stageName;
	}
    else
    {
      var randTree=roundToTwo(Math.random());
      if (randTree < .17)
        treeSprite = 'spr_tree3';
      else if (randTree < .34)
        treeSprite = 'spr_tree4';
      else if (randTree < .5)
        treeSprite = 'spr_tree6';
      else if (randTree < .66)
        treeSprite = 'spr_rock7';
      else if (randTree < .84)
        treeSprite = 'spr_cactus2';
      else
        treeSprite = 'spr_tree7';
      
      var randBush=roundToTwo(Math.random());
      if (randBush < .17)
        bushSprite = 'spr_bush2';
      else if (randBush < .34)
        bushSprite = 'spr_bush';
      else if (randBush < .5)
        bushSprite = 'spr_tree2';
      else if (randBush < .66)
        bushSprite = 'spr_bush3';
      else if (randBush < .84)
        bushSprite = 'spr_bush4';
      else
        bushSprite = 'spr_stump';
      
      var randRock=roundToTwo(Math.random());
      if (randRock < .17)
        rockSprite = 'spr_rock8';
      else if (randRock < .34)
        rockSprite = 'spr_rock5';
      else if (randRock < .5)
        rockSprite = 'spr_rock9';
      else if (randRock < .66)
        rockSprite = 'spr_rock4';
      else if (randRock < .84)
        rockSprite = 'spr_rock5';
      else
        rockSprite = 'spr_rock6';
      
      var randBackground=roundToTwo(Math.random());
      if (randBackground < .14)
        backgroundColor = 'rgb(68,132,14)';
      else if (randBackground < .28)
        backgroundColor = 'rgb(64,94,56)';
      else if (randBackground < .42)
        backgroundColor = 'rgb(41,62,34)';
      else if (randBackground < .56)
        backgroundColor = 'rgb(65,67,64)';
      else if (randBackground < .70)
        backgroundColor = 'rgb(165,170,79)';
      else if (randBackground < .84)
        backgroundColor = 'rgb(57,22,11)';
      else
        backgroundColor = 'rgb(8,146,238)';

      
      stageName = "Randomized Chaos";
	  document.getElementById("stageName").innerHTML = "Stage Name: " + stageName; 
    }
      };
      
// Game scene
// -------------
// Runs the core gameplay loop
Crafty.scene('Game', function() {
  // A 2D array to keep track of all occupied tiles
  this.occupied = new Array(Game.map_grid.width);
  for (var i = 0; i < Game.map_grid.width; i++) {
    this.occupied[i] = new Array(Game.map_grid.height);
    for (var y = 0; y < Game.map_grid.height; y++) {
      this.occupied[i][y] = false;
    }
  }
 
  // Player character, placed at 1, 1 on grid
  this.player = Crafty.e('PlayerCharacter').at(1, 1);
  this.occupied[this.player.at().x][this.player.at().y] = true;
  // Prevent the player from being stuck in corner
  this.occupied[this.player.at().x+1][this.player.at().y] = true;
  this.occupied[this.player.at().x][this.player.at().y+1] = true;
  this.occupied[this.player.at().x+1][this.player.at().y+1] = true;

  
  // Generate village at the corner of the map
  x= Game.map_grid.width-2;
  y= Game.map_grid.height-2;
  Crafty.e('Village').at(x, y);
  this.occupied[x][y] = true;
 //Prevent the village from being cornered
   this.occupied[x-1][y] = true;
   this.occupied[x][y-1] = true;
   this.occupied[x-1][y-1] = true;
 
  // Place a tree at every edge square on our grid of 16x16 tiles
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      var at_edge = x == 0 || x == Game.map_grid.width - 1 ||
                    y == 0 || y == Game.map_grid.height - 1;
 
      if (at_edge) {
        // Place a tree entity at the current tile
        Crafty.e('Tree').at(x, y);
        this.occupied[x][y] = true;
      } else if (Math.random() < 0.06 && !this.occupied[x][y]) {
        // Place a bush entity at the current tile
        var bush_or_rock = (Math.random() > 0.3) ? 'Bush' : 'Rock';
        Crafty.e(bush_or_rock).at(x, y);
        this.occupied[x][y] = true;
      }
    }
  }
  
  // Generate yellow coins on the map in random locations
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.03) {
        if (Crafty('YellowCoin').length < max_yellow_coins && !this.occupied[x][y]) {
          Crafty.e('YellowCoin').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
 
   // Generate red coins on the map in random locations
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.03) {
        if (Crafty('RedCoin').length < max_red_coins && !this.occupied[x][y]) {
          Crafty.e('RedCoin').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
  
  
  // Generate green coins on the map in random locations
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.03) {
        if (Crafty('GreenCoin').length < max_green_coins && !this.occupied[x][y]) {
          Crafty.e('GreenCoin').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
  
  // Generate blue coins on the map in random locations
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.03) {
        if (Crafty('BlueCoin').length < max_blue_coins && !this.occupied[x][y]) {
          Crafty.e('BlueCoin').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
  
  // Generate boots on the map in one random location
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.005) {
        if (Crafty('Boots').length < max_boots && !this.occupied[x][y]) {
          Crafty.e('Boots').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
  
  // Generate clocks on the map in two random locations
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.008) {
        if (Crafty('Clock').length < max_clocks && !this.occupied[x][y]) {
          Crafty.e('Clock').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
  
   // Generate multipliers on the map in one random location
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.005) {
        if (Crafty('Multiplier').length < max_multipliers && !this.occupied[x][y]) {
          Crafty.e('Multiplier').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
  
  // Generate multipliers on the map in one random location
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      if (Math.random() < 0.005) {
        if (Crafty('Flame').length < max_flames && !this.occupied[x][y]) {
          Crafty.e('Flame').at(x, y);
	  this.occupied[x][y] = true;
        }
      }
    }
  }
 
  // Generate an enemy
//  var max_enemies = 1;
//  for (var x = 0; x < Game.map_grid.width; x++) {
//    for (var y = 0; y < Game.map_grid.height; y++) {
//      if (Math.random() < 0.03) {
//        if (Crafty('Enemy').length < max_enemies && !this.occupied[x][y]) {
//          Crafty.e('Enemy').at(x, y);
//	  this.occupied[x][y] = true;
//        }
//      }
//    }
//  }

  // Enemy placed at 9, 9 on grid
//  var enemy = Crafty.e('Enemy').at(9, 9);
 // this.occupied[enemy.at().x][enemy.at().y] = true;

//  moves enemy
   //  var interval; //used to track the interval and call function
    // interval = setInterval(function() {enemy.move('e',8);},150);
 
  // Play a ringing sound to indicate the start of the journey
  Crafty.audio.play('ring');
 
  // Show the victory screen once all villages are visisted
  this.show_victory = this.bind('VillageVisited', function() {
    if (!Crafty('Village').length) {
      updateCoinCounts();
      updateCounter();
      updateStage();
      updateClocksCount()
      bootsTester();
      
      if ((stage%5) == 0)
      {
	stageDecider();
	Crafty.background(backgroundColor);
        Crafty.scene('Bonus');
      }
      else
      {
          stageDecider();
	  Crafty.background(backgroundColor);
	  Crafty.scene('Game');
      }
      
      
    }
  });
}, function() {
  // Remove our event binding from above so that we don't
  //  end up having multiple redundant event watchers after
  //  multiple restarts of the game
  this.unbind('VillageVisited', this.show_victory);
});
 
 
// Victory scene
// -------------
// Tells the player when they've won and lets them start a new game
Crafty.scene('Victory', function() {
  // Display some text in celebration of the victory
  Crafty.e('2D, DOM, Text')
    .text('Time is Up!')
    .attr({ x: 0, y: Game.height()/2 - 24, w: Game.width() })
    .css($text_css);
 
  // Give'em a round of applause!
  Crafty.audio.play('fanfare');

  // Save high score
  Parse.initialize("EL9rGBARwKQl3NL4HAQ2U4GxQYjXV8dDDvDDaTPe", "WQLflsIP1zoVHCZgNjpr95dtrmaqjCaCkWSbOSrU");
  var GameScore = Parse.Object.extend("GameScore");
  var gameScore = new GameScore();
   
  var userName = Parse.User.current().get("username");
  
  gameScore.save({
    score: score,
    playerName: userName,
    stage: stage,
    elapsedTime: elapsedTime,
    yellowCoinsCollected: yellowCoinsCollected,
    redCoinsCollected: redCoinsCollected,
    greenCoinsCollected: greenCoinsCollected,
    blueCoinsCollected: blueCoinsCollected,
    bootsCollected: bootsCollected,
    multipliersCollected: multipliersCollected,
    clocksCollected: clocksCollected,
    firesCollected: firesCollected
  }, {
    success: function(gameScore) {
      // The object was saved successfully.
      alert("High Score Added!");
    },
    error: function(gameScore, error) {
      // The save failed.
      // error is a Parse.Error with an error code and description.
       alert("failed!");
    }
  });

  // After a short delay, watch for the player to press a key, then restart
  // the game when a key is pressed
  //var delay = true;
  //setTimeout(function() { delay = false; }, 5000);
  
  //this.restart_game = Crafty.bind('KeyDown', function() {
  //  if (!delay) {
  //    Crafty.scene('Game');
 //   }
 // });
}, function() {
  // Remove our event binding from above so that we don't
  //  end up having multiple redundant event watchers after
  //  multiple restarts of the game
 // this.unbind('KeyDown', this.restart_game);
});

// Loading scene
// -------------
// Handles the loading of binary assets such as images and audio files
Crafty.scene('Loading', function(){
  // Draw some text for the player to see in case the file
  //  takes a noticeable amount of time to load
  Crafty.e('2D, DOM, Text')
    .text('Loading; please wait...')
    .attr({ x: 0, y: Game.height()/2 - 24, w: Game.width() })
    .css($text_css);
 
  // Load our sprite map image
  Crafty.load([
    'assets/images/16x16_forest_2.gif',
    'assets/images/hunter.png',
    'assets/images/coinColors.png',
    'assets/sounds/door_knock_3x.mp3',
    'assets/sounds/door_knock_3x.ogg',
    'assets/sounds/door_knock_3x.aac',
    'assets/sounds/board_room_applause.mp3',
    'assets/sounds/board_room_applause.ogg',
    'assets/sounds/board_room_applause.aac',
    'assets/sounds/candy_dish_lid.mp3',
    'assets/sounds/candy_dish_lid.ogg',
    'assets/sounds/candy_dish_lid.aac',
    'assets/images/itemspritesfinal.png',
    'assets/sounds/SwooshCombo.mp3',
    'assets/sounds/SwooshCombo.ogg',
    'assets/sounds/SwooshCombo.aac',
    'assets/images/femalehealer.png',
    'assets/images/femalemage.png',
    'assets/images/femaleninja.png',
    'assets/images/femaleranger.png',
    'assets/images/femalewarrior.png',
    'assets/images/malehealer.png',
    'assets/images/malemage.png',
    'assets/images/maleninja.png',
    'assets/images/maleranger.png',
    'assets/images/malewarrior.png',
    'assets/images/flame.png',
    'assets/images/trees.png',
    'assets/images/rocks.png',
    'assets/sounds/fanfare.mp3',
    'assets/sounds/fanfare.ogg',
    'assets/sounds/fanfare.aac',
    ], function(){
    // Once the images are loaded...
 
    // Define the individual sprites in the image
    // Each one (spr_tree, etc.) becomes a component
    // These components' names are prefixed with "spr_"
    //  to remind us that they simply cause the entity
    //  to be drawn with a certain sprite
    Crafty.sprite(16, 'assets/images/16x16_forest_2.gif', {
      spr_tree:    [0, 0],
      spr_bush:    [1, 0],
      spr_village: [0, 1],
      spr_rock:    [1, 1]
    });
    
    Crafty.sprite(16, 'assets/images/trees.png', {
      spr_stump:    [2, 0],
      spr_tree1:    [3, 0],
      spr_tree2:    [6, 0],
      spr_tree3:    [3, 1],
      spr_tree4:    [3, 2],
      spr_tree5:    [6, 2],
      spr_tree6:    [6, 3],
      spr_stump2:    [1, 5],
      spr_logs:    [1, 6],
      spr_cactus:    [3, 5],
      spr_bush2:    [0, 1],
      spr_bush3:    [1, 2],
      spr_cactus2: [5,0],
      spr_tree7: [1,1],
      spr_bush4: [2,1],
    });
    
    Crafty.sprite(16, 'assets/images/rocks.png', {
      spr_rock2:    [0, 0],
      spr_rock3:    [2, 0],
      spr_rock4:    [3, 0],
      spr_rock5:    [0, 1],
      spr_rock6:    [1, 1],
      spr_rock7:    [2, 1],
      spr_rock8:    [0, 2],
      spr_rock9:    [1, 2],
    });
    
    Crafty.sprite (16, 'assets/images/coinColors.png', {
      spr_yellow_coin:    [0, 0],
      spr_red_coin:       [1, 0],
      spr_green_coin:     [2, 0],
      spr_blue_coin:      [3, 0]
    });
    
    Crafty.sprite (16, 'assets/images/pickups.png', {
      spr_boots:    [0,0],
      spr_clock: [1,0],
      spr_coindouble: [2,0]
    });
    
    Crafty.sprite (16, 'assets/images/flame.png', {
      spr_flame: [0,0]
    });
 
 	Parse.initialize("EL9rGBARwKQl3NL4HAQ2U4GxQYjXV8dDDvDDaTPe", "WQLflsIP1zoVHCZgNjpr95dtrmaqjCaCkWSbOSrU");
	var currentUser = Parse.User.current();
    //Get the players role from parse
    var role=currentUser.get("class");
    //Get the players gender from parse
    var gender=currentUser.get("gender");
    //Set sprite
    var sprite='assets/images/'+gender+role+'.png';

 
 
    // Define the PC's sprite to be the first sprite in the third row of the
    //  animation sprite map
    Crafty.sprite(16, sprite, {
      spr_player:  [0, 2],
    }, 0, 2);
    
    
    //// Define the Enemy sprite animation
    //    // Define the PC's sprite to be the first sprite in the third row of the
    ////  animation sprite map
    //Crafty.sprite(16, 'assets/images/hunter.png', {
    //  spr_enemy:  [0, 2],
    //}, 0, 2);
 
    // Define our sounds for later use
    Crafty.audio.add({
      knock:     ['assets/sounds/door_knock_3x.mp3',
                  'assets/sounds/door_knock_3x.ogg',
                  'assets/sounds/door_knock_3x.aac'],
      applause:  ['assets/sounds/board_room_applause.mp3',
                  'assets/sounds/board_room_applause.ogg',
                  'assets/sounds/board_room_applause.aac'],
      ring:      ['assets/sounds/candy_dish_lid.mp3',
                  'assets/sounds/candy_dish_lid.ogg',
                  'assets/sounds/candy_dish_lid.aac'],
      coin:      ['assets/sounds/coin.mpg',
                  'assets/sounds/coin.ogg',
                  'assets/sounds/coin.aac'],
      speed:      ['assets/sounds/SwooshCombo.mp3',
                  'assets/sounds/SwooshCombo.ogg',
                  'assets/sounds/SwooshCombo.aac'],
      clocktick:  ['assets/sounds/clockticking.mp3',
                  'assets/sounds/clockticking.ogg',
                  'assets/sounds/clockticking.aac'],
      moneybooster:['assets/sounds/coinpowerup.mp3',
                  'assets/sounds/coinpowerup.ogg',
                  'assets/sounds/coinpowerup.aac'],
      flamenoise:['assets/sounds/flamenoise.mp3',
                  'assets/sounds/flamenoise.ogg',
                  'assets/sounds/flamenoise.aac'],
      fanfare:	['assets/sounds/fanfare.mp3',
                  'assets/sounds/fanfare.ogg',
                  'assets/sounds/fanfare.aac'],
    });
 
    // Now that our sprites are ready to draw, start the game
    Crafty.scene('Game');
  })
});


// Game scene
// -------------
// Runs the bonus gameplay loop
Crafty.scene('Bonus', function() {
  // A 2D array to keep track of all occupied tiles
  this.occupied = new Array(Game.map_grid.width);
  for (var i = 0; i < Game.map_grid.width; i++) {
    this.occupied[i] = new Array(Game.map_grid.height);
    for (var y = 0; y < Game.map_grid.height; y++) {
      this.occupied[i][y] = false;
    }
  }
 
  // Player character, placed at 1, 1 on grid
  this.player = Crafty.e('PlayerCharacter').at(1, 1);
  this.occupied[this.player.at().x][this.player.at().y] = true;

  // Generate village at the corner of the map
  x= Game.map_grid.width-2;
  y= Game.map_grid.height-2;
  Crafty.e('Village').at(x, y);
  this.occupied[x][y] = true;

 
  // Place a tree at every edge square on our grid of 16x16 tiles
  for (var x = 0; x < Game.map_grid.width; x++) {
    for (var y = 0; y < Game.map_grid.height; y++) {
      var at_edge = x == 0 || x == Game.map_grid.width - 1 ||
                    y == 0 || y == Game.map_grid.height - 1;
 
      if (at_edge) {
        // Place a tree entity at the current tile
        Crafty.e('Tree').at(x, y);
        this.occupied[x][y] = true;
      } 
    }
  }
  

    if (stage == 5)
  {
        // Generate yellow coins on the map in random locations
    for (var x = 6; x < Game.map_grid.width-6; x++) {
      for (var y = 6; y < Game.map_grid.height-6; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            Crafty.e('YellowCoin').at(x, y);
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }
  else if (stage ==10)
  {
            // Generate yellow coins on the map in random locations
    for (var x = 3; x < Game.map_grid.width-3; x++) {
      for (var y = 3; y < Game.map_grid.height-3; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            Crafty.e('YellowCoin').at(x, y);
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }
  else if (stage == 15)
  {
        // Generate yellow coins on the map in random locations
    for (var x = 6; x < Game.map_grid.width-6; x++) {
      for (var y = 6; y < Game.map_grid.height-6; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            Crafty.e('RedCoin').at(x, y);
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }
  else if (stage ==20)
  {
            // Generate yellow coins on the map in random locations
    for (var x = 3; x < Game.map_grid.width-3; x++) {
      for (var y = 3; y < Game.map_grid.height-3; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            Crafty.e('RedCoin').at(x, y);
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }
  else if (stage == 25)
  {
        // Generate yellow coins on the map in random locations
    for (var x = 6; x < Game.map_grid.width-6; x++) {
      for (var y = 6; y < Game.map_grid.height-6; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            Crafty.e('GreenCoin').at(x, y);
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }
  else if (stage ==30)
  {
            // Generate yellow coins on the map in random locations
    for (var x = 3; x < Game.map_grid.width-3; x++) {
      for (var y = 3; y < Game.map_grid.height-3; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            Crafty.e('BlueCoin').at(x, y);
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }
  else if (stage ==35)
  {
            // Generate yellow coins on the map in random locations
    for (var x = 3; x < Game.map_grid.width-3; x++) {
      for (var y = 3; y < Game.map_grid.height-3; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            Crafty.e('BlueCoin').at(x, y);
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }
  else
  {
            // Generate yellow coins on the map in random locations
    for (var x = 0; x < Game.map_grid.width; x++) {
      for (var y = 0; y < Game.map_grid.height; y++) {
        if (Math.random() < 1) {
          if (!this.occupied[x][y]) {
            if (Math.random() < .25)
	      Crafty.e('BlueCoin').at(x, y);
	    else if (Math.random() < .50)
	      Crafty.e('GreenCoin').at(x, y);
	    else if (Math.random() < .75)
	      Crafty.e('RedCoin').at(x, y);
	    else
	      Crafty.e('YellowCoin').at(x, y);
	    
        this.occupied[x][y] = true;
          }
        }
      }
    }
  }


  // Play a ringing sound to indicate the start of the journey
  Crafty.audio.play('ring');
 
  // Show the victory screen once all villages are visisted
  this.show_victory = this.bind('VillageVisited', function() {
    if (!Crafty('Village').length) {
      updateCoinCounts();
      updateCounter();
      updateStage();
      updateClocksCount()
      bootsTester();
      
      if ((stage%5) == 0)
      {
	stageDecider();
	Crafty.background(backgroundColor);
        Crafty.scene('Bonus');
      }
      else
      {
          stageDecider();
	  Crafty.background(backgroundColor);
	  Crafty.scene('Game');
      }
    }
  });
}, function() {
  // Remove our event binding from above so that we don't
  //  end up having multiple redundant event watchers after
  //  multiple restarts of the game
  this.unbind('VillageVisited', this.show_victory);
});


